package com.auth.ctl;

import com.auth.vo.TokenVo;
import com.client.common.vo.ClientResult;
import com.client.common.vo.ClientUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.el.parser.Token;
import org.apache.catalina.User;
import org.apache.catalina.users.MemoryUser;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 权限控制器
 *
 * @author dzh
 * @date 2023/1/29 16:57
 */
@RestController
public class AuthCtl {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("token")
    public ClientResult<TokenVo> token(ClientUser user) throws JsonProcessingException {
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        BoundValueOperations<String, String> ops = redisTemplate.boundValueOps("spring:auth:" + key);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        int minutes = 10;
        ops.set(json, Duration.of(minutes, ChronoUnit.MINUTES));
        long expire = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(minutes);
        TokenVo tokenVo = TokenVo.builder().token(key).expire(expire).build();
        return ClientResult.makeSuccess(tokenVo);
    }

    @GetMapping("user")
    public ClientResult<ClientUser> user(String token) throws JsonProcessingException {
        BoundValueOperations<String, String> ops = redisTemplate.boundValueOps("spring:auth:" + token);
        String json = ops.get();
        if (!StringUtils.hasText(json)) {
            return ClientResult.makeFail("token无效");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        ClientUser user = objectMapper.readValue(json, ClientUser.class);
        return ClientResult.makeSuccess(user);
    }
}
